﻿using NLog.Extensions.Logging;
using SqlSugar;
using System.Runtime.CompilerServices;

namespace WomanMotion.WebApi.Api.Utility
{
    /// <summary>
    /// Sqlsugar配置类
    /// </summary>
    public static class SqlsugarSetup
    {
        private static ILogger _logger;

        static SqlsugarSetup()
        {
            _logger = LoggerFactory.Create(builder => builder.AddNLog()).CreateLogger<Program>();
        }

        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,
        string dbName = "ConnectionStrings:PostgreSQL")
        {
            SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.PostgreSQL,
                ConnectionString = configuration[dbName],
                IsAutoCloseConnection = true,
            },
                db =>
                {
                    //单例参数配置，所有上下文生效
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        string strpars = "";
                        foreach (var par in pars)
                        {
                            string strvalue = "";
                            if (par.Value == null)
                            {
                                strvalue = "null";
                            }
                            else
                            {
                                strvalue = par.Value.ToString();
                            }
                            strpars += par.ParameterName + "=" + strvalue + "|";
                        }
                        strpars = strpars.TrimEnd('|');
                        //Console.WriteLine(sql);//输出sql
                        _logger.LogInformation(sql);
                        _logger.LogInformation(strpars);
                    };
                });
            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }
    }
}